package com.lanhao.aot.carrierintegration.postnl;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;

public class PostNLUtil {
	public static final Logger LOG = LoggerFactory.getLogger(PostNLUtil.class);

	// https://api-sandbox.postnl.nl/shipment/v2_2/label
	public static final String BASE_URL = "https://api-sandbox.postnl.nl";
	public static final String API_KEY = "8b0e829a-a452-48bc-9241-7c08a8645861"; // 测试环境
	
//	public static final String BASE_URL = "https://api.postnl.nl";
//	public static final String API_KEY = "ac064e6f-00f0-4716-9bb9-f0932826a8e1"; // 正式环境
	
	
	public static final String HEADER_KEY_NAME = "apikey";
	public static final String SHIPMENT_PATH = "/shipment/v2_2/label";
	public static final String COUNTRY_CODE = "NL";
	public static final String CUSTOMER_NUMBER = "10867397";
	public static final String CUSTOMER_CODE = "JESF";  // JESH
	public static final String COLLECTION_LOCATION = "100548";
//	public static final String PRODUCT_CODE = "3085";
	public static final String PRODUCT_CODE = "2285";
	
	// Customer number:10867397
	// Collection location (BLS):100548
	
	// AddressType  01	Receiver  02	Sender (if not in Customer/Address)
	
	public static void main(String[] args) {
		createLabel();
//		for (int i = 0; i < 10; i++) {
//			System.out.println(IdUtil.getSnowflakeNextIdStr());
//		}
	}

	private static void createLabel() {
		JSONObject body = new JSONObject();
		JSONObject customer = new JSONObject();
		
		JSONObject address = new JSONObject();
		address.put("AddressType", "02");  // Sender
		address.put("City", "Den Haag");
		address.put("CompanyName", "AnHe");
		address.put("Countrycode", COUNTRY_CODE);
		address.put("HouseNr", "3");
		address.put("Street", "Waldorpstraat");
		address.put("Zipcode", "2521CA");
		
		customer.put("Address", address);
		customer.put("CollectionLocation", COLLECTION_LOCATION);
		customer.put("CustomerCode", CUSTOMER_CODE);
		customer.put("CustomerNumber", CUSTOMER_NUMBER);
		customer.put("Email", "-");
		body.put("Customer", customer);
		
		
		JSONObject message = new JSONObject();
		String messageID = IdUtil.getSnowflakeNextIdStr();
		message.put("MessageID", messageID);
		String messageTime = DateUtil.format(new Date(), "dd-mm-yyyy hh:mm:ss");
		message.put("MessageTimeStamp", messageTime);
		message.put("Printertype", "GraphicFile|PDF");
		body.put("Message", message);
		
		JSONArray shipments = new JSONArray();
		JSONObject shipment = new JSONObject();
		
		JSONArray addresses = new JSONArray();
		JSONObject addressObject = new JSONObject();
		addressObject.put("AddressType", "01");  // Receiver
		addressObject.put("City", "Kerkrade");
		addressObject.put("Countrycode", COUNTRY_CODE);
//		addressObject.put("CompanyName", "Receiver company");
		addressObject.put("HouseNr", "20");
//		addressObject.put("HouseNrExt", "A");
		addressObject.put("Name", "KunKun");
		addressObject.put("Street", "Antwoordnummer");
		addressObject.put("Zipcode", "6460WB");
		addresses.add(addressObject);
		
		shipment.put("Addresses", addresses);
		
		
		JSONObject dimension = new JSONObject();
		dimension.put("Weight", "300");
		shipment.put("Dimension", "dimension");
		
		shipment.put("ProductCodeDelivery", PRODUCT_CODE);
		shipment.put("Reference", "-");
		shipment.put("Remark", "-");
		
		shipments.add(shipment);
		body.put("Shipments", shipments);
		
		LOG.info("请求PostNL，url={}，request={}，header={}", BASE_URL + SHIPMENT_PATH, body.toJSONString(), API_KEY);
		HttpResponse resp = HttpRequest.post(BASE_URL + SHIPMENT_PATH).header(HEADER_KEY_NAME, API_KEY)
				.body(body.toJSONString()).timeout(20000).execute();
		int status = resp.getStatus();
		String result = resp.body();
		LOG.info("请求PostNL，status={}, resp={}", status, result);
		JSONObject resultObject = JSON.parseObject(result);
		if(status == HttpStatus.HTTP_OK) {
			JSONArray responseShipments = resultObject.getJSONArray("ResponseShipments");
			JSONObject responseShipment = responseShipments.getJSONObject(0);
			String barcode = responseShipment.getString("Barcode");
			JSONArray labels = responseShipment.getJSONArray("Labels");
			JSONObject labelObject = labels.getJSONObject(0);
			String labelContent = labelObject.getString("Content");
			Base64.decodeToFile(labelContent, new File("D:/" + barcode + ".pdf"));
			LOG.info("成功获取单号：barcode={}", barcode);
		} else if(status == HttpStatus.HTTP_BAD_REQUEST) {
			
		} else {
			String error = resultObject.getString("message");
			LOG.info("请求PostNL失败，error={}", error);
		}
		
		try {
			FileUtils.write(new File("D:/aaaa.txt"), result, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
